package 图论.岛屿数量广搜版_200;
/*
        给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
        岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
        此外，你可以假设该网格的四条边均被水包围。

        示例 1：
        输入：grid = [
        ["1","1","1","1","0"],
        ["1","1","0","1","0"],
        ["1","1","0","0","0"],
        ["0","0","0","0","0"]
        ]
        输出：1
        示例 2：
        输入：grid = [
        ["1","1","0","0","0"],
        ["1","1","0","0","0"],
        ["0","0","1","0","0"],
        ["0","0","0","1","1"]
        ]
        输出：3
        提示：
        m == grid.length
        n == grid[i].length
        1 <= m, n <= 300
        grid[i][j] 的值为 '0' 或 '1'*/

import java.util.ArrayDeque;
import java.util.Deque;

/*  不需要回溯，因为dfs只是搜索 + 标记功能，第一个访问到陆地 -》将次数加一， 与它相连的陆地都标记以到过就可
* */
public class Solution {
    static boolean visit[][];
    static int[][] f = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

    public static void main(String[] args) {
        char[][] grid = {
                {'1', '1', '0', '0', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '1', '0', '0'},
                {'0', '0', '0', '1', '1'} };
        System.out.println(numIslands(grid));
    }
    public static int numIslands(char[][] grid) {
        visit = new boolean[grid.length][grid[0].length];
        int count = 0;
        for (int i = 0;i < grid.length; i ++){
            for (int j = 0; j < grid[0].length; j ++){
                // 先全部标记为没有找过，遇到第一个找到的就计数，再将与之相连的点标记
               if (!visit[i][j] && grid[i][j] == '1'){
                   count ++;
                   bfs(grid, visit, i, j);
               }
            }
        }
        return count;
    }
    public static void bfs(char[][] grid, boolean[][] visit, int raw, int col){
        // 队列，ArraySDeque是Deque接口下的实现类，有原来的add(),remove()方法，但是这些方法没有自动扩容
        // 等操作，超过空间会报错让自己解决，所以实现了，offer()---加入元素,poll()---拿出元素,peek()查看元素，操作来自动扩容等
        Deque<int[]> deque = new ArrayDeque<>();
        deque.offer(new int[]{raw, col});
        visit[raw][col] = true;
        while (!deque.isEmpty()){
            int[] t = deque.poll();
            for (int i = 0; i < 4; i ++){
                int dx = t[0] + f[i][0]; int dy = t[1] + f[i][1];
                if (dx < 0 || dy < 0 || dx >= grid.length || dy >= grid[0].length){
                    continue;
                }
                // 这就相当于结束条件，因为只有符合条件的才能继续遍历，和原来写终止语句相比 减少了遍历次数
                if (!visit[dx][dy] && grid[dx][dy] == '1') {
                    deque.offer(new int[]{dx, dy});
                    visit[dx][dy] = true;
                }
            }
        }

    }
}
